package com.hx.vending.controller;

import com.hx.vending.annotation.Accredit;
import com.hx.vending.bean.Admin;
import com.hx.vending.bean.AdminRole;
import com.hx.vending.bean.Role;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.service.IAdminRoleService;
import com.hx.vending.service.IAdminService;
import com.hx.vending.service.IRoleService;
import com.hx.vending.util.Base64Util;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/1/9.
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IAdminRoleService adminRoleService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     *管理员登录
     * @param account 账号
     * @param password 密码
     * @return
     */
    @RequestMapping("/loginAdmin")
    @ResponseBody
    public Msg loginAdmin(@RequestParam("account")String account, @RequestParam("password")String password){
        Admin admin = new Admin();
        if (ToolUtil.isNotEmpty(account)) {
            admin.setAdminAccount(account);
        }else{
            return Msg.fail().add("va_msg", "账号不能为空");
        }
        if (ToolUtil.isNotEmpty(password)) {
            admin.setAdminPassWord(password);
        }else{
            return Msg.fail().add("va_msg", "密码不能为空");
        }
        Admin a = adminService.selectByPrimary(admin);
        String adminId = String.valueOf(a.getAdminId());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String str = adminId+"_"+"A_"+uuid;
        String token = Base64Util.baseEncode(str);
        redisTemplate.boundValueOps(adminId+"A").set(token,Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return Msg.success().add("token",token);
        /*if(ToolUtil.isNotEmpty(a)){
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminRoleAdminId(a.getAdminId());
            AdminRole ar = adminRoleService.selectByPrimary(adminRole);
            redisTemplate.boundValueOps("roleName").set(ar.getAdminRoleRole().getRoleName(),Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
            redisTemplate.boundValueOps("roleId").set(ar.getAdminRoleRole().getRoleId(),Constants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
            return Msg.success();
        }else {
            return Msg.fail().add("va_msg", "未找到对应的账户信息");
        }*/
    }

    /**
     * 添加系统用户
     * @param admin
     * @return
     */
    @RequestMapping(value = "/saveAdmin",method = RequestMethod.POST)
    @ResponseBody
    @Accredit
    public Msg saveAdmin(@RequestBody Admin admin,BindingResult result){
        if(result.hasErrors()) {
            //校验失败，应该返回失败，在模态框中显示校验失败的错误信息
            Map<String, Object> map = new HashMap<String, Object>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors) {
                System.out.println("错误的字段名：" + fieldError.getField());
                System.out.println("错误信息：" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }else {
            if (ToolUtil.isNotEmpty(admin.getRoleIds())) {
                Admin admin1 = new Admin();
                admin1.setAdminAccount(admin.getAdminAccount());
                Admin aa = adminService.selectByPrimary(admin1);
                if(ToolUtil.isNotEmpty(aa)){
                    return Msg.fail().add("va_msg","该账号已存在");
                }
                admin.setAdminCreateTime(ToolUtil.currentTime());
                int result1 = adminService.insertSelective(admin);
                Admin a = adminService.selectByPrimary(admin);
                if (result1 != 0) {
                    AdminRole adminRole = new AdminRole();
                    adminRole.setAdminRoleAdminId(a.getAdminId());
                    String[] str = admin.getRoleIds().split(",");
                    for (int i = 0; i < str.length; i++) {
                        Role role = new Role();
                        role.setRoleId(Integer.parseInt(str[i]));
                        adminRole.setAdminRoleRoleId(roleService.selectByPrimary(role).getRoleId());
                        adminRoleService.insertSelective(adminRole);
                    }
                }
                return Msg.success();
            }else{
               return Msg.fail().add("va_msg","角色不能为空");
            }
        }
    }

    /**
     * 查询全部系统用户
     * @param pageNum
     * @param content
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/getAdminAll")
    @ResponseBody
    @Accredit
    public Msg getAdminAll(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,String content) throws UnsupportedEncodingException {
        Integer pageStart = (pageNum - 1) * 10;
        Map<String,Object> map = new HashMap<>();
        map.put("pageStart",pageStart);
        if(ToolUtil.isNotEmpty(content)){
            map.put("content",content);
        }
        List<Admin> adminList = adminService.selectAdmin(map);
        for(Admin admin:adminList){
            Integer[] integers = adminRoleService.selectRoleByAdmin(admin.getAdminId());
            admin.setRoleIdStr(integers);
        }
        return Msg.success().add("adminList",adminList);
    }

    /**
     * 删除用户
     * @param adminIds
     * @return
     */
    @RequestMapping(value = "/deleteAdmin/{adminIds}",method = RequestMethod.DELETE)
    @ResponseBody
    @Accredit
    public Msg deleteAdmin(@PathVariable("adminIds") String adminIds){
        String[] strs = adminIds.split("-");
        List<Integer> integerList = new ArrayList<>();
        for(int i = 0;i < strs.length;i++){
            integerList.add(Integer.parseInt(strs[i]));
        }
        if (CollectionUtils.isEmpty(integerList)) {

            integerList = null;
        }
        int x = adminService.deleteByAdminId(integerList);
        if (x > 0){
            adminRoleService.deleteByAdminId(integerList);
            return Msg.success();
        }
        return Msg.fail();
    }

    /**
     * 修改用户
     * @param admin
     * @return
     */
    @RequestMapping("/editAdmin")
    @ResponseBody
    @Accredit
    public Msg editAdmin(@RequestBody Admin admin){
        String roleIds = admin.getRoleIds();
        String[] strs = roleIds.split(",");
        List<Integer> integerList = new ArrayList<>();
        integerList.add(admin.getAdminId());
        int result = adminRoleService.deleteByAdminId(integerList);
        if(result > 0){
            int i = adminService.updateByPrimaryKey(admin);
            if (i > 0){
                for(int x = 0;x < strs.length;x++){
                    AdminRole adminRole = new AdminRole();
                    adminRole.setAdminRoleAdminId(admin.getAdminId());
                    adminRole.setAdminRoleRoleId(Integer.parseInt(strs[x]));
                    adminRoleService.insertSelective(adminRole);
                }
                return Msg.success();
            }
        }
        return Msg.fail();
    }

    /**
     * 检查账号是否可用
     * @param adminAccount
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/checkAdminAccount",method=RequestMethod.POST)
    public Msg checkAdminAccount(@RequestParam("adminAccount")String adminAccount){
        Admin admin = new Admin();
        admin.setAdminAccount(adminAccount);
        Admin a = adminService.selectByPrimary(admin);
        if(a == null){
            return Msg.success();
        }else{
            return Msg.fail().add("va_msg", "管理员账号已存在,不能重复");
        }
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg logout(){
        Admin admin = (Admin) redisTemplate.boundValueOps("admin").get();
        if(ToolUtil.isNotEmpty(admin)){
            redisTemplate.delete("admin");
            redisTemplate.delete("roleName");
            redisTemplate.delete("roleId");
        }
        return Msg.success();
    }


    /**
     * 获取阿里云配置数据
     * @return
     */
    @PostMapping("/selectOSSBucket")
    @ResponseBody
    public Msg selectOSSBucket() {

        //获取properties中的值
        Resource resource = new ClassPathResource("OSSBucket.properties");
        Properties props=null;
        try {
            props = PropertiesLoaderUtils.loadProperties(resource);
            String endpoint=props.getProperty("aliyun.oss.endpoint");
            String accessKeyId=props.getProperty("aliyun.oss.accessKeyId");
            String accessKeySecret=props.getProperty("aliyun.oss.accessKeySecret");
            String bucketName=props.getProperty("aliyun.oss.bucketName");
            String path=props.getProperty("aliyun.oss.path");

            return Msg.success().add("endpoint", endpoint).add("accessKeyId", accessKeyId).add("accessKeySecret", accessKeySecret).add("bucketName", bucketName).add("path", path);
        } catch (IOException e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }

}
